﻿using System;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class PaymentControl : RSBaseUserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!Page.IsPostBack)
            {
                if (Request.QueryString["action"] == "edit" || Request.QueryString["action"] == "add")
                {
                    btnSavePayment.Visible = true;
                    //btnDeletePayment.Visible = true;
                }
                else
                {
                    btnEditPayment.Visible = true;
                    SetControlEnabledState(false);
                }

                if (Request.QueryString["action"] == "add")
                {
                    txtInvoiceId.Text = Request.QueryString["invoiceid"];
                    hfLocationId.Value = Request.QueryString["locationid"];
                }
            }

        }
        protected void ddlPaymentType_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            String paymenttype = ddlPaymentType.SelectedItem.Text.Trim();
            if (paymenttype.Contains("Check") || paymenttype.Contains("Cash"))
            {
                SetCreditCardEnabledState(false);
                RequiredFieldValidator_txtCCExpireDT.Enabled = false;
            }
            else
            {
                SetCreditCardEnabledState(true);
            }
        }
        private void SetCreditCardEnabledState(bool bstate)
        {
            txtCCExpireDT.Enabled = bstate;
            txtCCName.Enabled = bstate;
            txtCCNumber.Enabled = bstate;
            txtCVV.Enabled = bstate;
            if (!bstate)
            {
                txtCCExpireDT.BackColor = System.Drawing.Color.Gainsboro;
                txtCCName.BackColor = System.Drawing.Color.Gainsboro;
                txtCCNumber.BackColor = System.Drawing.Color.Gainsboro;
                txtCVV.BackColor = System.Drawing.Color.Gainsboro;
            }
            else
            {
                txtCCExpireDT.BackColor = System.Drawing.Color.White;
                txtCCName.BackColor = System.Drawing.Color.White;
                txtCCNumber.BackColor = System.Drawing.Color.White;
                txtCVV.BackColor = System.Drawing.Color.White;
            }
        }
        public void SetControlEnabledState(bool bstate = false)
        {
            
            RSSBMCommonFunctions.SetControlsEnabledState(this, bstate);
        }
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            string prevurl = string.Empty;
            if (Session["PreviousURL"] != null)
                prevurl = Session["PreviousURL"].ToString();
            else
                prevurl = Request.UrlReferrer.ToString();
            Response.Redirect(prevurl);
        }
        private void LoadPaymentTypeDDL(int companyid)
        {
            SqlCommand myCommand;
            SqlDataReader myDataReader;
            String sqlSELECT = "SELECT TypeID, TypeName FROM [rs_tblType] WHERE CompanyID=@companyid AND Category='PAYMENT_CAT'";
            SqlParameter param = new SqlParameter();
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);
            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            ddlPaymentType.Items.Clear();
            ddlPaymentType.DataSource = myDataReader;
            ddlPaymentType.DataTextField = "TypeName";
            ddlPaymentType.DataValueField = "TypeID";
            ddlPaymentType.DataBind();
            ddlPaymentType.Items.Insert(0, new ListItem("< Please select >", "0"));
            myConnection.Close();
        }

        protected void btnEditPayment_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                int LocationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value);
                int InvoiceId = txtInvoiceId.Text == "" ? 0 : Convert.ToInt32(txtInvoiceId.Text);
                int PaymentId = txtPaymentId.Text == "" ? 0 : Convert.ToInt32(txtPaymentId.Text);
                Response.Redirect("~/RS/SBM/RSManagePayment.aspx?action=edit&locationid=" + LocationId + "&invoiceid=" + InvoiceId + "&paymentid=" + PaymentId);
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }
        protected void btnSavePayment_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int CompanyId = userIdentity.RSCompanyId;

            int LocationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value);
            int InvoiceId = txtInvoiceId.Text == "" ? 0 : Convert.ToInt32(txtInvoiceId.Text);
            int PaymentId = txtPaymentId.Text == "" ? 0 : Convert.ToInt32(txtPaymentId.Text);

            string PaymentDate = txtPaymentDT.Text.Trim();
            string PaymentNote = txtPaymentNote.Text.Trim();
            int PaymentTypeId = Convert.ToInt32(ddlPaymentType.SelectedValue);
            float PaymentAmount = txtPaymentAmount.Text == "" ? 0 : Convert.ToSingle(txtPaymentAmount.Text);
            string CCName = txtCCName.Text.Trim();
            string CCNumber = txtCCNumber.Text.Trim();
            string CCExpireDT = txtCCExpireDT.Text.Trim();
            int CVV = txtCVV.Text == "" ? 0 : Convert.ToInt32(txtCVV.Text);

            SqlCommand sqlCmd = new SqlCommand();

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@PaymentId", SqlDbType.Int, 0, ParameterDirection.Input, PaymentId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@InvoiceId", SqlDbType.Int, 0, ParameterDirection.Input, InvoiceId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);

            if (PaymentDate.Trim().Length > 0)
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@PaymentDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(PaymentDate));
            if (CCExpireDT.Trim().Length > 0)
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CCExpireDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(CCExpireDT));
            
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@PaymentNote", SqlDbType.NVarChar, -1, ParameterDirection.Input, PaymentNote);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@PaymentAmount", SqlDbType.Money, 0, ParameterDirection.Input, PaymentAmount);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@PaymentTypeId", SqlDbType.Int, 0, ParameterDirection.Input, PaymentTypeId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CCName", SqlDbType.NVarChar, 50, ParameterDirection.Input, CCName);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CCNumber", SqlDbType.NVarChar, 50, ParameterDirection.Input, CCNumber);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CVV", SqlDbType.Int, 0, ParameterDirection.Input, CVV);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
            SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSavePayment");
            SQLHelper.ExecuteScalarCmd(sqlCmd);

            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
            ucModalActionMessageControl.ShowModal("Payment Successfully Saved!", "RSInvoiceDetail.aspx?locationid=" + LocationId + "&invoiceid=" + InvoiceId, true);


        }

        protected void btnDeletePayment_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int companyid = userIdentity.RSCompanyId;

                int paymentid = txtPaymentId.Text == "" ? 0 : Convert.ToInt32(txtPaymentId.Text);
                int invoiceid = txtInvoiceId.Text == "" ? 0 : Convert.ToInt32(txtInvoiceId.Text);

                if (companyid > 0 && invoiceid > 0 && paymentid > 0)
                {
                    SqlCommand sqlCmd = new SqlCommand();
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@paymentid", SqlDbType.Int, 0, ParameterDirection.Input, paymentid);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@invoiceid", SqlDbType.Int, 0, ParameterDirection.Input, invoiceid);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, companyid);
                    SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblPayment WHERE InvoiceId=@InvoiceId AND  PaymentId=@PaymentId AND CompanyId=@companyid");
                    SQLHelper.ExecuteScalarCmd(sqlCmd);
                    int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                    string prevurl = string.Empty;
                    if (Session["PreviousURL"] != null)
                        prevurl = Session["PreviousURL"].ToString();
                    else
                        prevurl = Request.UrlReferrer.ToString();
                    ucModalActionMessageControl.ShowModal("Payment deleted successfully!", prevurl, true);
                }
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }

        public void LoadPaymentData(int companyid, int locationid, int invoiceid, int paymentid)
        {
            LoadPaymentTypeDDL(companyid);

            String strSQL = "SELECT * FROM [rs_tblPayment] WHERE paymentid=@paymentid AND invoiceid=@invoiceid AND companyid=@companyid";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(strSQL, myConnection);
            SqlDataReader myDataReader;

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@invoiceid";
            param.Value = invoiceid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@paymentid";
            param.Value = paymentid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if (myDataReader.HasRows)
            {
                myDataReader.Read();
                hfLocationId.Value = myDataReader["LocationId"].ToString();
                txtInvoiceId.Text = myDataReader["InvoiceId"].ToString();
                txtPaymentId.Text = myDataReader["PaymentId"].ToString();
                txtPaymentAmount.Text = myDataReader["PaymentAmount"].ToString();
                if (myDataReader["PaymentDT"] != DBNull.Value)
                {
                    DateTime paymentdt = Convert.ToDateTime(myDataReader["PaymentDT"]);
                    txtPaymentDT.Text = paymentdt.ToShortDateString();
                }
                if(myDataReader["PaymentTypeId"] != DBNull.Value)
                    ddlPaymentType.SelectedValue = myDataReader["PaymentTypeId"].ToString();
                txtCCName.Text = myDataReader["CCName"].ToString();
                txtCCNumber.Text = myDataReader["CCNumber"].ToString();
                if (myDataReader["CCExpireDT"] != DBNull.Value)
                {
                    DateTime ccexpiredt = Convert.ToDateTime(myDataReader["CCExpireDT"]);
                    txtCCExpireDT.Text = ccexpiredt.ToShortDateString();
                }
                txtCVV.Text = myDataReader["CVV"].ToString();
                txtPaymentNote.Text = myDataReader["PaymentNote"].ToString();

                if (Request.QueryString["action"] == "edit")
                    btnDeletePayment.Visible = true;
    
            }
        }
    }
}